package cn.xaut.查找表;

import java.util.*;

public class demo290 {

    // 大佬解法
    public boolean wordPattern2(String pattern, String s) {

        String[] words = s.split(" ");
        if (words.length != pattern.length())
            return false;

        char[] p = pattern.toCharArray();

        Map<Object, Integer> map = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            if (!Objects.equals(map.put(p[i], i), map.put(words[i], i)))
                return false;
        }
        return true;
    }
    
    // 我的解法
    public boolean wordPattern(String pattern, String s) {

        String[] words = s.split(" ");
        if (words.length != pattern.length())
            return false;
        
        Map<Character, String> map = new HashMap<>();
        
        char[] p = pattern.toCharArray();
        for (int i = 0; i < p.length; i++) {
            if (map.containsKey(p[i])) {
                if (!map.get(p[i]).equals(words[i]))
                    return false;
            } else
                map.put(p[i], words[i]);
        }

        Set<String> set = new HashSet<>();
        for (String x : map.values()) {
            if (!set.add(x)) 
                return false;
        }
        
        return true;
    }

    public static void main(String[] args) {

        System.out.println(new demo290().wordPattern2("abba", "dog cat cat dog"));//true
        System.out.println(new demo290().wordPattern2("abba", "dog cat cat fish"));//false
        System.out.println(new demo290().wordPattern2("aaaa", "dog cat cat dog"));//false
        System.out.println(new demo290().wordPattern2("abba", "dog dog dog dog"));//false
        System.out.println(new demo290().wordPattern2("aaa", "aa aa aa aa"));//false
//        Map<Integer, Integer> map = new HashMap<>();
//        for (int i = 0; i < 5; i++) 
//            System.out.println(map.put(1, 1));
    }
}
